package com.gnerv.author.controller;

import com.gnerv.author.entity.FileManage;
import com.gnerv.author.entity.R;
import com.gnerv.author.service.IFileService;
import javafx.geometry.Pos;
import org.flywaydb.core.internal.util.FileCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @author Gnerv LiGen
 * @description
 * @data 2019/7/25
 */
@RestController
@RequestMapping(value = "/blog/file")
public class FileController {

    @Autowired
    IFileService fileService;

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public R uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        FileManage fileManage = fileService.save(file);
        return R.back().data("fileManage", fileManage);
    }

    @RequestMapping(value = "open/{bId}", method = RequestMethod.GET)
    public void download(@PathVariable("bId") String bId, HttpServletResponse response){
        try {
            FileManage fileManage = fileService.select(bId);
            File download = fileService.download(bId);
            //设置文件为直接下载 不可在线打开
            response.setContentType("application/octet-stream");
            //获取文件原始名称
            String filenameByUuid = fileManage.getName();
            //设置文件名和编码
            String fileName = URLEncoder.encode(filenameByUuid, "UTF-8");
            response.setHeader( "Content-Disposition", "attachment;filename=" +fileName);
            FileCopyUtils.copy(new FileInputStream(download), response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
